﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IngredSubTool
{
    /// <summary>
    /// Interaction logic for SearchResultsView.xaml
    /// </summary>
    public partial class SearchResultsView : UserControl, IAppPage
    {

        public SearchResultsView()
        {
            InitializeComponent();
            Menu.Content = new SideMenu();
            TermTitle.Text += MainWindow.session.searchTerm;
            SearchField.Text = MainWindow.session.searchTerm;

            //Do search for matching results.
            List<Substitution> matchingSubs = new List<Substitution>();

            foreach (Substitution nextSub in DataLoader.Substitutions)
            {
                Boolean subMatches = true;

                //Check for match with ingredient name.
                if (!nextSub.IngredientName.ToLower().Contains(MainWindow.session.searchTerm.ToLower()))
                    subMatches = false;

                //Ensure substitution matches categories.
                foreach (SearchCategory nextCat in DataLoader.SearchCategories)
                    if (nextCat.Enabled && !nextSub.Categories.ToLower().Contains(nextCat.Name.ToLower()))
                    {
                        subMatches = false;
                        break;
                    }

                // Additional clause so that searching an empty search bar does not bring up the entire substitution list
                if (subMatches && MainWindow.session.searchTerm != "")
                {
                    matchingSubs.Add(nextSub);
                }
            }

            ResultsGrid.ItemsSource = matchingSubs;
        }

        private void Back(object sender, RoutedEventArgs e)
        {
            PageSwitcher.Switch(new SearchView());
        }

        private void DoSearch(object sender, RoutedEventArgs e)
        {
            MainWindow.session.searchTerm = SearchField.Text;
            PageSwitcher.Switch(new SearchResultsView());
        }

        private void SearchField_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                DoSearch(sender, e);
            }
        }
    }
}
